import streamlit as st
import pandas as pd
import os
from PIL import Image

# 设置页面配置
st.set_page_config(
    page_title="豆瓣电影Top250",
    page_icon="🎬",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 获取项目根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 加载数据
@st.cache_data
def load_data():
    csv_path = os.path.join(BASE_DIR, 'top250.csv')
    df = pd.read_csv(csv_path)
    
    # 处理genres为列表
    df['genres'] = df['genres'].str.split(',')
    
    # 获取所有电影类型
    all_genres = set()
    for genres in df['genres']:
        if isinstance(genres, list):
            all_genres.update([g.strip() for g in genres])
    all_genres = sorted(all_genres)
    
    return df, all_genres

# 加载数据
df, all_genres = load_data()

# 应用标题
st.title("🎬 豆瓣电影Top250")

# 创建侧边栏
with st.sidebar:
    st.header("电影筛选")
    selected_genre = st.selectbox("选择电影类型", ["全部"] + all_genres)
    search_query = st.text_input("搜索电影名称")
    
    st.markdown("---")
    st.markdown("**数据信息**")
    st.markdown(f"总电影数: {len(df)}")

# 电影卡片显示函数
def show_movie_card(row, col):
    with col:
        # 使用绝对路径获取图片
        img_path = os.path.join(BASE_DIR, 'images', f"{row['movie_id']}.jpg")
        try:
            img = Image.open(img_path)
            st.image(img, use_container_width=True, caption=row['title'])
        except FileNotFoundError:
            st.warning(f"封面未找到: {img_path}")
        except Exception as e:
            st.error(f"加载封面出错: {e}")
        
        st.markdown(f"**{row['title']}**")
        st.markdown(f"⭐ **评分**: {row['douban_rating']}")
        st.markdown(f"🎭 **类型**: {', '.join(row['genres'])}")
        
        if st.button("查看详情", key=f"detail_{row['movie_id']}"):
            st.session_state.selected_movie = row
            st.session_state.page = "detail"

# 电影详情页
def show_movie_detail():
    movie = st.session_state.selected_movie
    st.button("← 返回列表", on_click=lambda: st.session_state.update({"page": "list"}))
    
    col1, col2 = st.columns([1, 2])
    
    with col1:
        img_path = os.path.join(BASE_DIR, 'images', f"{movie['movie_id']}.jpg")
        try:
            img = Image.open(img_path)
            st.image(img, use_container_width=True)
        except FileNotFoundError:
            st.warning(f"封面未找到: {img_path}")
        
        st.markdown(f"**评分**: ⭐ {movie['douban_rating']}")
        st.markdown(f"**上映日期**: {movie['release_date']}")
    
    with col2:
        st.markdown(f"**导演**: {movie['directors']}")
        st.markdown(f"**编剧**: {movie['writers']}")
        st.markdown(f"**主演**: {movie['actors']}")
        st.markdown(f"**类型**: {', '.join(movie['genres'])}")
        st.markdown(f"**国家/地区**: {movie['country']}")
        st.markdown(f"**语言**: {movie['language']}")
        st.markdown("---")
        st.markdown(f"**剧情简介**:")
        st.markdown(f"> {movie['synopsis']}")

# 初始化session state
if "page" not in st.session_state:
    st.session_state.page = "list"
    st.session_state.selected_movie = None

# 主页面逻辑
if st.session_state.page == "list":
    filtered_df = df.copy()
    
    if selected_genre != "全部":
        filtered_df = filtered_df[filtered_df['genres'].apply(
            lambda x: selected_genre in [g.strip() for g in x] if isinstance(x, list) else False
        )]
    
    if search_query:
        filtered_df = filtered_df[filtered_df['title'].str.contains(search_query)]
    
    st.subheader(f"🎞️ 电影列表 (共 {len(filtered_df)} 部)")
    
    cols = st.columns(4)
    for idx, row in filtered_df.iterrows():
        show_movie_card(row, cols[idx % 4])
        if (idx + 1) % 4 == 0 and (idx + 1) < len(filtered_df):
            cols = st.columns(4)
else:
    show_movie_detail()

# CSS样式优化
st.markdown("""
<style>
    .stButton button {
        width: 100%;
        transition: all 0.3s;
    }
    .stButton button:hover {
        background-color: #f0f2f6;
    }
    .stImage {
        border-radius: 8px;
        transition: transform 0.3s;
    }
    .stImage:hover {
        transform: scale(1.03);
    }
    .warning {
        color: orange;
        font-size: 0.9em;
    }
</style>
""", unsafe_allow_html=True)